#include "../logs/log.hpp"

// 测试是否支持扩展，根据时间扩展日志落地模块
enum class TimeGap
{
    GAP_SECOND,
    GAP_MINUTE,
    GAP_HOUR,
    GAP_DAY
};

class RollByTimeSink : public Mylog::LogSink
{
public:
    RollByTimeSink(const std::string basename, TimeGap gap_type)
        : _basename(basename)
    {
        switch (gap_type)
        {
        case TimeGap::GAP_SECOND:
            _gap_size = 1;
            break;
        case TimeGap::GAP_MINUTE:
            _gap_size = 60;
            break;

        case TimeGap::GAP_HOUR:
            _gap_size = 3600;
            break;
        case TimeGap::GAP_DAY:
            _gap_size = 3600 * 24;
            break;
        }
        _cur_gap = Mylog::util::Date::now() / _gap_size;
        std::string filename = createNewFilename();
        Mylog::util::File::createDirectory(Mylog::util::File::path(filename));
        _ofs.open(filename, std::ios::binary | std::ios::app);
        assert(_ofs.is_open());
    }
    void log(const char *data, size_t len) override
    {
        time_t cur = Mylog::util::Date::now();
        if (cur / _gap_size != _cur_gap)
        {
            _cur_gap = cur / _gap_size;
            _ofs.close();
            std::string filename = createNewFilename();
            _ofs.open(filename, std::ios::binary | std::ios::app);
            assert(_ofs.is_open());
        }
        _ofs.write(data, len);
        assert(_ofs.good());
    }

private:
    // 进行大小判断，超出指定大小则创建新文件
    std::string createNewFilename()
    {
        // 获取当前时间，以时间来构造文件扩展名
        time_t t = Mylog::util::Date::now();
        struct tm lt;
        localtime_r(&t, &lt);
        std::stringstream ss;
        ss << _basename;
        ss << lt.tm_year + 1900;
        ss << lt.tm_mon + 1;
        ss << lt.tm_mday;
        ss << lt.tm_hour;
        ss << lt.tm_min;
        ss << lt.tm_sec;
        ss << ".log";
        return ss.str();
    }

private:
    std::string _basename;
    std::ofstream _ofs;
    size_t _cur_gap;  // 当前处于第几个时间段
    size_t _gap_size; // 时间段大小
};


int main()
{
    std::unique_ptr<Mylog::LoggerBuilder> bulider(new Mylog::GlobalLoggerBuilder());
    bulider->bulidLoggerName("anync_logger");
    bulider->bulidLoggerLevel(Mylog::LogLevel::value::WARN);
    bulider->bulidLoggerType(Mylog::LoggerType::LOGGER_ASYNC);
    bulider->bulidFormatter("[%c][%f:%l]%m%n");
    bulider->buildSink<RollByTimeSink>("./logfile/roll-async-by-time.log", TimeGap::GAP_SECOND);
    Mylog::Logger::ptr logger = bulider->build();
    size_t cur = Mylog::util::Date::now();
    while(Mylog::util::Date::now() < cur + 5)
    {
        logger->fatal("这是一条测试日志");
        usleep(1000);
    }
    return 0;
}